const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');

// 模拟用户数据库，实际使用中应替换为真实数据库操作
const users = [
    {
        id: 1,
        username: 'gao',
        passwordHash: bcrypt.hashSync('password1', 10),
        studyDuration: 120, // 自习时长，单位：分钟
        focusDegree: 0.8, // 自习专注度，范围 0 - 1
        personalGoal: '每天自习 3 小时',
        encouragementSlogan: '坚持就是胜利，你一定可以的！',
        avatar: 'https://a.520gexing.com/uploads/allimg/2021042109/uqaqhuvavt0.jpg' // 头像 URL
    },
    {
        id: 2,
        username: 'zhan',
        passwordHash: bcrypt.hashSync('password2', 10),
        studyDuration: 90,
        focusDegree: 0.7,
        personalGoal: '完成一套模拟试卷',
        encouragementSlogan: '每一次努力都在靠近成功，加油！',
        avatar: 'https://www.keaitupian.cn/cjpic/frombd/0/253/1152107840/119779555.jpg'
    }
];


// 获取用户信息接口
router.get('/userInfo', (req, res) => {
    const { username } = req.query;
    const user = users.find(u => u.username === username);
    if (!user) {
        return res.status(404).json({
            success: false,
            message: '未找到该用户'
        });
    }

    res.json({
        success: true,
        message: '获取用户信息成功',
        user: {
            username: user.username,
            studyDuration: user.studyDuration,
            focusDegree: user.focusDegree,
            personalGoal: user.personalGoal,
            encouragementSlogan: user.encouragementSlogan,
            avatar: user.avatar
        }
    });
});

// 更新用户信息接口
router.put('/userInfo', async (req, res) => {
    const { username, studyDuration, focusDegree, personalGoal, encouragementSlogan, avatar } = req.body;

    const userIndex = users.findIndex(u => u.username === username);
    if (userIndex === -1) {
        return res.status(404).json({
            success: false,
            message: '未找到该用户'
        });
    }

    if (studyDuration) {
        users[userIndex].studyDuration = studyDuration;
    }
    if (focusDegree) {
        users[userIndex].focusDegree = focusDegree;
    }
    if (personalGoal) {
        users[userIndex].personalGoal = personalGoal;
    }
    if (encouragementSlogan) {
        users[userIndex].encouragementSlogan = encouragementSlogan;
    }
    if (avatar) {
        users[userIndex].avatar = avatar;
    }

    res.json({
        success: true,
        message: '用户信息更新成功',
        user: {
            username: users[userIndex].username,
            studyDuration: users[userIndex].studyDuration,
            focusDegree: users[userIndex].focusDegree,
            personalGoal: users[userIndex].personalGoal,
            encouragementSlogan: users[userIndex].encouragementSlogan,
            avatar: users[userIndex].avatar
        }
    });
});

module.exports = router;